package dev.ece.suit.loader.models.fbx;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;

import dev.ece.suit.loader.Material;

public class FBXMaterial extends Material {

	public final static String MATERIAL = "Material";
	
	public final static String PROPERTY_DIFFUSE = "Diffuse";
	
	public final static String PROPERTY_AMBIENT = "Ambient";
	
	public final static String PROPERTY_SPECULAR = "Specular";
	
	public final static String PROPERTY_EMISSIVE = "Emissive";
	
	public final static String PROPERTY_SHININESS = "Shininess";
	
	private long id;
	
	public static FBXMaterial[] parseFBXMaterial(List<FBXElement> materialElements) {
		if(materialElements != null && !materialElements.isEmpty()) {
			FBXMaterial[] materials = new FBXMaterial[materialElements.size()];
			FBXElement props = null;
			for(int i=0; i<materials.length; i++) {
				materials[i] = new FBXMaterial();
				if(materialElements.get(i).getProperties().length > 0) {
					materials[i].id = (long) materialElements.get(i).getProperties()[0].getValue();
				}
				props = materialElements.get(i).findChildren(FBXModelLoader.PROPERTIES70)[0];
				for(FBXElement prop: props.getChildren()) {
					if(StringUtils.equals(FBXModelLoader.P, prop.getId()) && prop.hasProperties()) {
						if(StringUtils.equals(PROPERTY_DIFFUSE, (String) prop.getProperties()[0].getValue())) {
							materials[i].getDiffuse().set(
									((Double) prop.getProperties()[4].getValue()).floatValue(), 
									((Double) prop.getProperties()[5].getValue()).floatValue(), 
									((Double) prop.getProperties()[6].getValue()).floatValue());
						} else if(StringUtils.equals(PROPERTY_SPECULAR, (String) prop.getProperties()[0].getValue())) {
							materials[i].getSpecular().set(
									((Double) prop.getProperties()[4].getValue()).floatValue(), 
									((Double) prop.getProperties()[5].getValue()).floatValue(), 
									((Double) prop.getProperties()[6].getValue()).floatValue());
						} else if(StringUtils.equals(PROPERTY_SHININESS, (String) prop.getProperties()[0].getValue())) {
							materials[i].setShininess(((Double) prop.getProperties()[4].getValue()).floatValue());
						}
					}
				}
			}
			return materials;
		}
		return null;
	}
	
	public static Map<Long, FBXMaterial> toFBXMaterialMap(FBXMaterial[] materials) {
		Map<Long, FBXMaterial> result = new ConcurrentHashMap<Long, FBXMaterial>();
		if(materials != null) {
			for(FBXMaterial material: materials) {
				result.put(material.getId(), material);
			}
		}
		return result;
	}

	@Override
	protected void setTextureName(String textureName) {
		super.setTextureName(textureName);
	}

	public long getId() {
		return id;
	}
	
}
